/**
 * Copyright (C) 2009 alex <me@alex.0x08.org>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package uber.netbsd.community.dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.jdo.Extent;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;
import uber.netbsd.community.Loggered;

/**
 * Generic persistence tier manager. Papa of all other managers.
 * @author alex
 */
public class GenericManager<T> extends Loggered {

    protected Class<T> clazz;

    /**
     * own persistence manager to work with backend jdo framework (datanucleus for now)
     */
    protected static PersistenceManager persist = StoreManager.getFactory().getPersistenceManager();

   

    public GenericManager(Class<T> cl) {
            this.clazz=cl;
    }

    /**
     * remove object
     * @param id object's id
     */
    public void delete(Integer id) {

        T obj = get(id);
        if (obj!=null)
        persist.deletePersistent(obj);
    }

    /** Gets the object with the corresponding ID, or null if it does not exist. */
    public T get(Integer id) {
        Query q = persist.newQuery("SELECT FROM " + clazz.getName() + " WHERE id == :id");
        List results = (List) q.execute(id);
        if (results==null || results.isEmpty())
            return null;
        return (T) results.get(0);
    }

    /** Returns a list of all objects */
    public List<T> getAll() {

        List<T> out = new ArrayList<T>();

            Extent ex = persist.getExtent(clazz, true);
            Iterator i = ex.iterator();
            while (i.hasNext()) {
                T obj = (T) i.next();
                out.add(obj);
            }
        return Collections.unmodifiableList(out);
    }


    /** Static helper so that it can be used both by the instance method, and in static init. */
    public T saveOrUpdate(T obj) {


        T out= null;
        Transaction tx = null;
        try {
            tx = persist.currentTransaction();
            tx.begin();

            out = persist.makePersistent(obj);
            tx.commit();


            persist.flush();
            
            getLogger().debug("__saved object "+obj);

        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }
            getLogger().error(e.getLocalizedMessage(),e);
        } finally {

            return out;
        }
    }
}
